//
//  HomeView.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 16.03.25.
//

import SwiftUI

struct HomeView: View {
    
    @Environment(\.presentToast) var presentToast
    
    private var needInit: Bool = false
    @State var isTrail = false
    @State var loadEvent = false
    @State var dataLoaded = false
    @Binding var reloadTrigger: Bool
    @StateObject var viewModel: HomeViewModel = HomeViewModel()
    @EnvironmentObject var bookSelection: BookSelection
    @State var date = Date()
    @State var navigationToBookManager = false
    @State var navigationToBudget = false
    @State var navigationToBudgetForAdd = false
    @State var showAddAccounting = false
    @State var showDetailSheet = false
    // 删除记账数据确认弹窗
    @State var showDeleteDetailConfirm = false
    @State var deleteDetail: AccountingDetailCombine? = nil
    @State var sheetDetail: AccountingDetailCombine? = nil
    @State var navigationToDetail: Bool = false
    @State var editDetail: AccountingDetailCombine? = nil
    
    @State var homeActionSheetShow = false
    @State var actionSheetType : HomeActionSheetType = .trialGuide
    
    init(reloadTrigger: Binding<Bool>) {
        _reloadTrigger = reloadTrigger
    }
    
    var body: some View {
        NavigationStack {
            ZStack {
                if viewModel.isLoading {
                    ProgressView()
                } else {
                    VStack(spacing : 0) {
                        HomeTitleView(onTrailGuideClick: {
                            actionSheetType = .trialGuide
                            homeActionSheetShow = true
                        }).padding(.horizontal, 20)
                        List {
                            HomeHeadView(
                                date: $date,
                                book: $bookSelection.currentBook,
                                onBookClick: {
                                    if self.isTrail {
                                        actionSheetType = .trialGuide
                                        homeActionSheetShow = true
                                    } else {
                                        navigationToBookManager = true
                                    }
                                },
                                onDateLeftClick: { date in
                                    viewModel.loadData(month: date.toYearMonth())
                                },
                                onDateRightClick: { date in
                                    viewModel.loadData(month: date.toYearMonth())
                                }
                            )
                            .koiListRowClear()
                            .padding(EdgeInsets(top: 16, leading: 20, bottom: 0, trailing: 20))
                            
                            OverviewAreaAccountingView(itemData: viewModel.overviewAreaData)
                                .koiListRowClear()
                                .padding(EdgeInsets(top: 10, leading: 20, bottom: 0, trailing: 20))
                            
                            Button(action: {
                                if isTrail {
                                    actionSheetType = .trialGuide
                                    homeActionSheetShow = true
                                } else {
                                    if viewModel.totalBudgetAmount == 0 {
                                        navigationToBudgetForAdd = true
                                    } else {
                                        navigationToBudget = true
                                    }
                                }
                            }) {
                                BudgetOverviewView(
                                    totalBudgetAmount: $viewModel.totalBudgetAmount,
                                    expenseAmount: $viewModel.expenseAmount,
                                    usePercent: $viewModel.usePercent,
                                    surplusAmount: $viewModel.surplusAmount
                                )
                            }
                            .koiListRowClear()
                            .padding(EdgeInsets(top: 16, leading: 20, bottom: 0, trailing: 20))

                            ForEach($viewModel.detailRowGroupList) { detailRowGroup in
                                VStack (spacing: 0){
                                    DetailGroupTitleView(item: detailRowGroup)
                                        .padding(EdgeInsets(top: 16, leading: 20, bottom: 8, trailing: 20))
                                    VStack(spacing: 0) {
                                        ForEach(detailRowGroup.groupData) { detail in
                                            Button(action: {
                                                sheetDetail = detail.wrappedValue
                                                navigationToDetail = true
                                            }) {
                                                DetailRowView(item: detail)
                                                    .contentShape(Rectangle())
                                            }.buttonStyle(PlainButtonStyle())
                                        }
                                    }
                                    .padding(.vertical, 4)
                                    .background(Color.koiColorBackgroundItem)
                                    .cornerRadius(16)
                                    .padding(EdgeInsets(top: 0, leading: 20, bottom: 0, trailing: 20))
                                }
                                .koiListRowClear()
                            }
                            Color.clear.frame(height: 90)
                                .listRowInsets(EdgeInsets())
                                .listRowSeparator(.hidden)
                                .listRowBackground(Color.clear)
                        }
                        .listStyle(PlainListStyle())
                        .scrollContentBackground(.hidden)
                    }
                    .navigationDestination(isPresented: $navigationToDetail, destination: {
                        if let detail = sheetDetail {
                            DetailRecordView(
                                item: detail,
                                onDeleteClick: {
                                    deleteDetail = detail
                                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
                                        actionSheetType = .deleteConfirm
                                        homeActionSheetShow = true
                                    }
                                },
                                onEditClick: {
                                    editDetail = detail
                                    // NotificationCenter.default.post(Notification(name: .openAdd, object: detail))
                                })
                            
                        } else {
                            EmptyView()
                        }
                    })
//                    .sheet(item: $sheetDetail) { detail in
//                        DetailRecordView(
//                            item: detail,
//                            onDeleteClick: {
//                                deleteDetail = detail
//                                DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
//                                    actionSheetType = .deleteConfirm
//                                    homeActionSheetShow = true
//                                }
//                            },
//                            onEditClick: {
//                                editDetail = detail
//                                // NotificationCenter.default.post(Notification(name: .openAdd, object: detail))
//                            }
//                        ).presentationDetents([.medium])
//                    }
                }
            }
            .navigationDestination(
                isPresented: $navigationToBookManager,
                destination: { BookManagerView() }
            )
            .navigationDestination(
                isPresented: $navigationToBudget,
                destination: { BudgetManagerView() })
            .navigationDestination(
                isPresented: $navigationToBudgetForAdd,
                destination: { BudgetManagerView(forAdd: true) })
            .sheet(item: $editDetail, onDismiss: {
                editDetail = nil
                viewModel.loadData()
            }) { editDetail in
                AddAccountingView(selectedDetail: editDetail).presentationDetents([.large])
            }
            .actionSheet(isPresented: $homeActionSheetShow) {
                switch actionSheetType {
                case .trialGuide:
                    self.ActionSheetGrialGuide()
                case .deleteConfirm:
                    ActionSheet(
                        title: Text("确定要删除「\(deleteDetail?.getTitle() ?? "")」吗？"),
                        message: Text("记账数据删除后不可恢复，请确认是否删除？"),
                        buttons: [
                            .destructive(Text("确认删除")) {
                                viewModel.delete(detail: deleteDetail)
                            },
                            .cancel(Text("取消"))
                        ])
                }
                
            }
            .onChange(of: viewModel.deleteState) { value in
                if value == "success" {
                    presentToast(.init(message: "已删除"))
                    viewModel.loadData()
                }
            }
            // 当外部触发信号变化时，重新加载数据
            .onChange(of: reloadTrigger) { _ in
                viewModel.loadData()
            }
            .onChange(of: bookSelection.currentBook) { _ in
                print("home view onChange bookSelection")
                viewModel.loadData()
            }
            .onDisappear {
                KoiEvent.homeReload.removeObserver(self)
            }
            .onAppear {
                print("home view onAppear \(dataLoaded)")
                if !dataLoaded {
                    dataLoaded = true
                    viewModel.initData()
                }
                if loadEvent {
                    loadEvent = false
                    viewModel.loadData()
                }
                KoiEvent.homeReload.addObserver { _ in
                    loadEvent = true
                }
                isTrail = KoiAccountingUserManager.standard.isTrail()
            }
        }
    }
}

enum HomeActionSheetType {
    case trialGuide, deleteConfirm
}

@available(iOS 18.0, *)
#Preview {
    @Previewable @State var reloadTrigger = false
    @Previewable @StateObject var bookSelection = BookSelection()
    HomeView(reloadTrigger: $reloadTrigger).environmentObject(bookSelection)
}
